package com.hvgroup.modules.sanic.web;

import com.hvgroup.annotation.rest.AnonymousPostMapping;
import com.hvgroup.modules.sanic.domain.dto.QaSessionDto;
import com.hvgroup.modules.sanic.domain.qo.QaQuestionQuery;
import com.hvgroup.modules.sanic.service.DifyQAService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/dify")
@Api(tags = "系统:会话管理")
public class DifyChatController {


    private final DifyQAService difyChatService;

    /**
     * 调用 DiFy 接口，流式返回 LLM 回答内容（Server-Sent Events）
     */
    @PostMapping(value = "/ws_answer", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> wsAnswer(@RequestBody Map<String, Object> body) {
        try {
//            String result =  difyChatService.processQuestion(body);
//            return new ResponseEntity<>(result,HttpStatus.OK);
            difyChatService.wsProcessQuestion(body);
            return ResponseEntity.ok("Dify 已启动流式应答，通过 WebSocket 推送中");

        } catch (Exception e) {
            log.error("Error invoking DiFy", e);
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "DiFy 流式回答失败");
        }
    }

    /**
     * TODO userId
     * 调用 DiFy 接口，流式返回 LLM 回答内容（Server-Sent Events）
     * 1. 携带chat_id → 根据chat_id继续会话
     * 2. 不携带则为新开窗口, 自动生成
     */
    @AnonymousPostMapping(value = "/get_answer", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<ServerSentEvent<String>> getAnswer(@RequestBody Map<String, Object> body) {
    public Flux<ServerSentEvent<String>> getAnswer(@RequestBody QaQuestionQuery body) {
//        Long userId = SecurityUtils.getCurrentUserId();
//        String user = SecurityUtils.getCurrentUsername();
//        body.setUser(user);
//        body.setUserId(userId);
        body.setUser(String.valueOf(body.getUserId()));
        return difyChatService.fluxProcessQuestion(body);
    }

    @AnonymousPostMapping(value = "/get_answer2", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<ServerSentEvent<String>> getAnswer(@RequestBody Map<String, Object> body) {
    public Flux<ServerSentEvent<String>> getAnswer2(@RequestBody QaQuestionQuery body) {
        body.setUser(String.valueOf(body.getUserId()));
        return difyChatService.fluxProcessQuestion2(body);
    }

    /**
     * dify问题建议  需要chat_id, conversationId
     */
    @AnonymousPostMapping(value = "/get_dify_suggested", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<ServerSentEvent<String>> getAnswer(@RequestBody Map<String, Object> body) {
    public Mono<ResponseEntity<String>> getSuggested(@RequestBody QaQuestionQuery body) {
//        Long userId = SecurityUtils.getCurrentUserId();
//        String user = SecurityUtils.getCurrentUsername();
//        body.setUser(user);
//        body.setUserId(userId);
        body.setUser(String.valueOf(body.getUserId()));

        return difyChatService.fluxProcessSuggested(body)
                .map(json -> ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(json))
                .onErrorResume(e -> {
                    log.error("调用失败: {}", e.getMessage(), e);
                    return Mono.just(ResponseEntity
                            .status(HttpStatus.INTERNAL_SERVER_ERROR)
                            .contentType(MediaType.TEXT_PLAIN)
                            .body("Dify 查询失败: " + e.getMessage()));
                });
    }


    /**
     * 点赞/点踩记率
     *
     * @param body {id:记录id, rating:-1踩,1赞}
     * @return 评价成功!
     */
    @Deprecated
    @AnonymousPostMapping(value = "/rating_answer", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> ratingAnswer(@RequestBody Map<String, Object> body) {
        try {
            difyChatService.ratingAnswer(body);
            return ResponseEntity.ok("评价成功!");
        } catch (Exception e) {
            log.error("评价失败", e);
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "评价失败");
        }
    }

    /**
     * 删除聊天记录
     *
     * @param body {ids:聊天记录id集合}
     * @return 评价成功!
     */
    @AnonymousPostMapping(value = "/delete_message", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> deleteMessage(@RequestBody Map<String, Object> body) {
        difyChatService.deleteMessage(body);
        return ResponseEntity.ok("删除成功!");
    }


    /**
     * 删除会话列表
     *
     * @param body {chatId:会话id}
     * @return 评价成功!
     */
    @AnonymousPostMapping(value = "/delete_session", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> deleteSession(@RequestBody Map<String, Object> body) {
            difyChatService.deleteSession(body);
        return ResponseEntity.ok("删除成功!");
    }

    /**
     * 修改会话名称
     *
     * @param body {chatId:会话id, title:标题}
     * @return 评价成功!
     */
    @AnonymousPostMapping(value = "/update_session", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> updateSession(@RequestBody QaSessionDto body) {
        difyChatService.updateSession(body);
        return ResponseEntity.ok("修改成功!");
    }

}


